import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Input, Modal, Form, Select, message, Image, Upload } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { listUserByPage, removeUser, adminUpdateUser, add } from '@/api/userController';
import { LoadingOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import ImgCrop from 'antd-img-crop';
import { withAdminAuth } from '@/components/AdminAuth';

interface UserData {
  id: string;
  username: string;
  email: string;
  userRole: string;
  nickName: string;
  phone: string;
  gender: number;
  wxcode: string;
  userProfile: string;
  avatarUrl: string;
  createTime: string;
  updateTime: string;
  address: string;
  password?: string;
}

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

function UserManagement() {
  const [users, setUsers] = useState<UserData[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserData | null>(null);
  const [form] = Form.useForm();
  const [imageUrl, setImageUrl] = useState<string>();
  const [uploadLoading, setUploadLoading] = useState(false);
  const [modalType, setModalType] = useState<'edit' | 'add'>('edit');
  const [modalTitle, setModalTitle] = useState('编辑用户信息');
  
  // 搜索条件
  const [searchForm] = Form.useForm();

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const values = await searchForm.validateFields()
        .catch(() => ({}));
      
      const res = await listUserByPage({
        current,
        pageSize,
        ...values,
      });
      
      if (res.code === 200 && res.data) {
        setUsers(res.data.records);
        setTotal(parseInt(res.data.total));
      } else {
        message.error(res.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表出错:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [current, pageSize]);

  const handleAdd = () => {
    setModalType('add');
    setModalTitle('新增用户');
    setEditingUser(null);
    setImageUrl('');
    form.resetFields();
    setEditModalVisible(true);
  };

  const handleEdit = (record: UserData) => {
    setModalType('edit');
    setModalTitle('编辑用户信息');
    setEditingUser(record);
    setImageUrl(record.avatarUrl);
    form.setFieldsValue({
      nickName: record.nickName,
      gender: record.gender,
      phone: record.phone,
      wxCode: record.wxcode,
      userProfile: record.userProfile,
      avatarUrl: record.avatarUrl,
      email: record.email,
      address: record.address,
      userRole: record.userRole,
      id: record.id
    });
    setEditModalVisible(true);
  };

  const handleDelete = async (userId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      onOk: async () => {
        try {
          const res = await removeUser({ userId });
          if (res.code === 200) {
            message.success('删除成功');
            fetchUsers();
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      if (modalType === 'edit' && editingUser) {
        const updateData = {
          ...values,
          id: editingUser.id,
          avatarUrl: imageUrl
        };
        
        const res = await adminUpdateUser(updateData);
        if (res.code === 200) {
          message.success('更新成功');
          setEditModalVisible(false);
          fetchUsers();
        } else {
          message.error(res.message || '更新失败');
        }
      } else if (modalType === 'add') {
        const res = await add({
          ...values,
          avatarUrl: imageUrl
        });
        if (res.code === 200) {
          message.success('添加用户成功');
          setEditModalVisible(false);
          fetchUsers();
        } else {
          message.error(res.message || '添加用户失败');
        }
      }
    } catch (error: any) {
      message.error(error.message || '操作失败');
    }
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setUploadLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setUploadLoading(false);
        const newAvatarUrl = info.file.response.data;
        setImageUrl(newAvatarUrl);
        form.setFieldsValue({ avatarUrl: newAvatarUrl });
        message.success('头像上传成功！');
      } else {
        setUploadLoading(false);
        message.error(info.file.response.message || '头像上传失败！');
      }
    } else if (info.file.status === 'error') {
      setUploadLoading(false);
      message.error('头像上传失败，请重试！');
    }
  };

  const columns: ColumnsType<UserData> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '头像',
      dataIndex: 'avatarUrl',
      key: 'avatarUrl',
      width: 80,
      render: (avatarUrl) => (
        <Image
          src={avatarUrl}
          alt="avatar"
          width={40}
          height={40}
          style={{ objectFit: 'cover' }}
          preview={{
            maskClassName: 'customize-mask',
            mask: <div>查看大图</div>
          }}
        />
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (gender) => {
        if (gender === 0) return '男';
        if (gender === 1) return '女';
        return '未知';
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '微信号',
      dataIndex: 'wxcode',
      key: 'wxcode',
    },
    {
      title: '角色',
      dataIndex: 'userRole',
      key: 'userRole',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-4">
      <div className="mb-4">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={fetchUsers}
        >
          <Form.Item name="username">
            <Input placeholder="用户名" />
          </Form.Item>
          <Form.Item name="email">
            <Input placeholder="邮箱" />
          </Form.Item>
          <Form.Item name="phone">
            <Input placeholder="手机号" />
          </Form.Item>
          <Form.Item name="gender">
            <Select placeholder="性别" allowClear style={{ width: 100 }}>
              <Select.Option value={0}>男</Select.Option>
              <Select.Option value={1}>女</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleAdd}>
              新增用户
            </Button>
          </Form.Item>
        </Form>
      </div>
      
      <div className="overflow-x-auto">
        <div className="min-w-[1500px]">
          <Table 
            columns={columns} 
            dataSource={users}
            rowKey="id"
            loading={loading}
            pagination={{
              total,
              current,
              pageSize,
              onChange: (page, size) => {
                setCurrent(page);
                setPageSize(size);
              },
            }}
          />
        </div>
      </div>

      <Modal
        title={modalTitle}
        open={editModalVisible}
        onOk={handleSave}
        onCancel={() => setEditModalVisible(false)}
        okText="确认"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          {modalType === 'edit' && (
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
          )}

          {modalType === 'add' && (
            <>
              <Form.Item 
                name="username" 
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 4, message: '用户名至少4个字符' }
                ]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
              
              <Form.Item 
                name="password" 
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' }
                ]}
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            </>
          )}

          <Form.Item label="头像">
            <ImgCrop rotationSlider>
              <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="http://localhost:8081/api/file/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
                data={{
                  biz: 'user_avatar'
                }}
                withCredentials={true}
              >
                {imageUrl ? (
                  <img 
                    src={imageUrl} 
                    alt="avatar" 
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                  />
                ) : (
                  <div>
                    {uploadLoading ? <LoadingOutlined /> : <PlusOutlined />}
                    <div style={{ marginTop: 8 }}>上传头像</div>
                  </div>
                )}
              </Upload>
            </ImgCrop>
          </Form.Item>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6">
            <Form.Item
              name="nickName"
              label="昵称"
              rules={[{ required: true, message: '请输入昵称' }]}
            >
              <Input placeholder="请输入昵称" />
            </Form.Item>

            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>

            <Form.Item
              name="gender"
              label="性别"
            >
              <Select placeholder="请选择性别">
                <Select.Option value={0}>男</Select.Option>
                <Select.Option value={1}>女</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="userRole"
              label="用户角色"
              rules={[{ required: true, message: '请选择用户角色' }]}
            >
              <Select placeholder="请选择用户角色">
                <Select.Option value="user">普通用户</Select.Option>
                <Select.Option value="admin">管理员</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="phone"
              label="手机号码"
            >
              <Input placeholder="请输入手机号码" />
            </Form.Item>

            <Form.Item
              name="wxCode"
              label="微信"
            >
              <Input placeholder="请输入微信号" />
            </Form.Item>
          </div>

          <Form.Item
            name="userProfile"
            label="个人简介"
          >
            <Input.TextArea 
              placeholder="请输入个人简介" 
              rows={3}
            />
          </Form.Item>

          <Form.Item
            name="address"
            label="地址"
          >
            <Input.TextArea 
              placeholder="请输入地址" 
              rows={3}
              disabled={modalType === 'edit'}
              className={modalType === 'edit' ? 'bg-gray-50' : ''}
            />
          </Form.Item>

          <Form.Item name="avatarUrl" hidden>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default withAdminAuth(UserManagement); 